using System;
using System.Web.Mvc;
using System.Web;

namespace VietThinks.Website.ActionFilter
{
    public class StaffAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var staffAuth = filterContext.HttpContext.Request.Cookies[AuthenticationService.StaffAuthCookieName];
            
            if (staffAuth == null)
            {
                string pathToRedirect = filterContext.HttpContext.Request.Url.AbsolutePath;

                string urlToRedirect = string.Format("~/admin/login?ReturnUrl={0}", pathToRedirect);

                filterContext.Result = new RedirectResult(urlToRedirect);
                //shouldn't use below statment bc when go out this function and 
                //other place have a exception then system raise a exception "Cannot redirect after HTTP headers have been sent."
                //filterContext.HttpContext.Response.Redirect(urlToRedirect, true);
            }
        }
    }

    public class RootAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var staffAuth = filterContext.HttpContext.Request.Cookies[AuthenticationService.StaffAuthCookieName];

            if (staffAuth == null || staffAuth.Name != System.Configuration.ConfigurationManager.AppSettings["DeploymentUserAuthorization"])
            {
                string pathToRedirect = filterContext.HttpContext.Request.Url.AbsolutePath;

                string urlToRedirect = string.Format("~/admin/login?ReturnUrl={0}", pathToRedirect);

                filterContext.Result = new RedirectResult(urlToRedirect);
                //shouldn't use below statment bc when go out this function and 
                //other place have a exception then system raise a exception "Cannot redirect after HTTP headers have been sent."
                //filterContext.HttpContext.Response.Redirect(urlToRedirect, true);
            }
        }
    }
}
